


from django.db.models.signals import pre_save, post_save, pre_delete, post_delete
from django.dispatch import receiver
from django.core.cache import cache
from .models import Book, BookLoan, Author
import logging

logger = logging.getLogger(__name__)

@receiver(pre_save, sender=Book)
def book_pre_save(sender, instance, **kwargs):
    if not instance.slug:
        instance.slug = instance.title.lower().replace(' ', '-')
    logger.info(f"Preparing to save book: {instance.title}")

@receiver(post_save, sender=Book)
def book_post_save(sender, instance, created, **kwargs):
    if created:
        logger.info(f"New book created: {instance.title}")
    else:
        logger.info(f"Book updated: {instance.title}")
    # 清除相关缓存
    cache.delete(f'book_{instance.id}_details')

@receiver(pre_delete, sender=Book)
def book_pre_delete(sender, instance, **kwargs):
    logger.warning(f"Book being deleted: {instance.title}")

@receiver(post_delete, sender=Book)
def book_post_delete(sender, instance, **kwargs):
    logger.warning(f"Book deleted: {instance.title}")
    # 清除相关缓存
    cache.delete(f'book_{instance.id}_details')

@receiver(post_save, sender=BookLoan)
def update_book_status_on_loan(sender, instance, created, **kwargs):
    if created and instance.return_date is None:
        # 当图书被借出时，可以更新图书状态
        Book.objects.filter(id=instance.book.id).update(status='on_loan')

# 自定义信号
from django.dispatch import Signal

book_published = Signal(providing_args=["book", "publisher"])
book_returned = Signal(providing_args=["book", "user"])

@receiver(book_published)
def handle_book_published(sender, **kwargs):
    book = kwargs['book']
    publisher = kwargs.get('publisher')
    logger.info(f"Book {book.title} published by {publisher.name if publisher else 'unknown publisher'}")
    # 可以在这里添加通知订阅者、更新索引等逻辑

@receiver(book_returned)
def handle_book_returned(sender, **kwargs):
    book = kwargs['book']
    user = kwargs['user']
    logger.info(f"Book {book.title} returned by {user.username}")
    # 可以在这里添加更新库存、发送确认邮件等逻辑